# -*- coding: utf-8 -*-
'''
sklearn实现决策树
'''
import configparser
import numpy as np
from sklearn import tree
from sklearn.externals import joblib
from sklearn.metrics import classification_report

conf = configparser.ConfigParser()
cofigFile = 'lenseCofig.ini'   # 定义配置文件

# 读取数据
with open(".//data//lenses.txt") as f:
    lense = [inst.strip().split('\t') for inst in f.readlines()]
lense = np.array(lense).T
lenseLabels = ['age', 'prescript', 'astigmatic', 'tearRate', 'y']

# 数据编码
def encoder(data):
    labels = np.unique(data)
    labels_encoder = {}
    for index, label in enumerate(labels):
        labels_encoder[label] = index
    return labels_encoder

#　写配置，以便预测时transform
def make_config(section, node):
    conf.read(cofigFile)
    conf.add_section(section) 
    for key, value in node.items():
        conf.set(section, key, str(value))
    conf.write(open(cofigFile,"w")) 

def make_train(lense, lenseLabels):
    for index, lenseLabel in enumerate(lenseLabels):
        labels_encoder = encoder(lense[index])
        make_config(lenseLabel, labels_encoder)
        for i in range(len(lense[index])):
            lense[index][i] = labels_encoder[lense[index][i]]    
    lense = lense.astype('int32').T
    return lense

lense = make_train(lense, lenseLabels)
X = [i[:-1] for i in lense]
Y = [i[-1] for i in lense]

# 训练模型，限制树的最大深度4
clf = tree.DecisionTreeClassifier()
# 拟合模型
clf.fit(X, Y)
# 保存本地模型，以复用
modelName = "Lenses.model"
joblib.dump(clf, './/model//'+modelName)

# 预测新样本，注意传参
yp = clf.predict(X)
print(classification_report(Y, yp))


